﻿using StarryEdge.Core.Device;
using StarryEdge.Core.Enums;
using StarryEdge.Core.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace StarryEdge.Device.Connections
{
    public class SerialPortFunc : ICommunication
    {
        private SerialPort _serialPort;
        private IProtocol _protocol;

        public SerialPortFunc(DeviceInfoModel model, bool dtr = false, bool rts = false)
        {
            _DeviceInfo = model;
            _serialPort = new SerialPort(model.IPCOM, model.Port, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One);
            _serialPort.ReadBufferSize = 512;
            _serialPort.WriteBufferSize = 512;
            _serialPort.DtrEnable = dtr;
            _serialPort.RtsEnable = rts;
        }
        private DeviceInfoModel _DeviceInfo;
        public DeviceInfoModel DeviceInfo => _DeviceInfo;

        public void Close()
        {
            if (_serialPort.IsOpen && _serialPort != null)
            {
                _serialPort.Close();
            }
        }

        public bool Open()
        {
            if (!_serialPort.IsOpen)
            {
                try
                {
                    _serialPort.Open();
                }
                catch (Exception)
                {
                    return false;
                }
            }
            return _serialPort.IsOpen;
        }

        public byte[] Receive()
        {
            byte[] data = new byte[512];
            int length = _serialPort.Read(data, 0, 512);
            return data.Take(length).ToArray();
        }

        public bool Send(byte[] data)
        {
            _serialPort.Write(data, 0, data.Length);
            return true;
        }
    }
}
